// pages/goods/list/index.js
import {
  getGoodsList
} from '../../../api/goods'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    goodsList: [], // 商品列表数据
    isFinish: false, // 判断数据是否加载完毕，
    isLoading: false,
    page: '1', // 页码
    limit: '10', // 每页条数
    category1Id: '', // 一级分类id
    category2Id: '', // 二级分类id
    total: null // 总条数
  },
  // 获取商品列表数据
  async getGoodsList(params, callback) {
    this.data.isLoading = true
    const res = await getGoodsList(params)
    this.data.isLoading = false
    const {
      data: {
        records,
        total
      }
    } = res
    callback && callback()
    this.setData({
      goodsList: [...this.data.goodsList, ...records],
      total
    })
  },
  // 上拉加载
  onReachBottom() {
    if (this.data.isLoading) return
    // goodslist的长度大于总条数则return
    if (this.data.goodsList.length >= this.data.total) return this.setData({
      isFinish: true
    })
    // 每次触发则页码数+1
    this.setData({
      page: `${parseInt(this.data.page)+1}`
    })

    this.getGoodsList(this.data)
  },
  // 下拉刷新
  onPullDownRefresh() {
    // 对相关数据重置
    this.setData({
      goodsList: [],
      isFinish: false,
      page: "1"
    })
    // 发起请求传入一个回调，用于数据回来之后关闭下拉刷新
    this.getGoodsList(this.data, () => {
      setTimeout(() => {
        wx.stopPullDownRefresh()
      }, 1000)
    })
  },
  onLoad({
    category1Id,
    category2Id
  }) {
    // 获取一级分类id和二级分类id并赋值
    this.setData({
      category1Id,
      category2Id
    })
    this.getGoodsList(this.data)
  },
    // 转发朋友，群聊功能
    onShareAppMessage() {
      return {
        title: "真爱有你",
        path: '/pages/index/index',
        imageUrl: '../../../../../assets/images/love.jpg'
      }
    },
    onShareTimeline() {
  
    },

})